{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [],
   "source": [
    "import base64\n",
    "import json\n",
    "import requests\n",
    " \n",
    "class BaiduPicIndentify:\n",
    "    def __init__(self,img):\n",
    "        self.AK = \"3ooIrdR1rI8XX1oY52TLnGST\"\n",
    "        self.SK = \"08ySYCOcXx1mrAHoTUdD6Qus4akn37Bt\"\n",
    "        self.img_src = img\n",
    "        self.headers = {\n",
    "            \"Content-Type\": \"application/json; charset=UTF-8\"\n",
    "        }\n",
    " \n",
    "    def get_accessToken(self):\n",
    "        host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + self.AK + '&client_secret=' + self.SK\n",
    "        response = requests.get(host, headers=self.headers)\n",
    "        json_result = json.loads(response.text)\n",
    "        return json_result['access_token']\n",
    " \n",
    "    def img_to_BASE64(self,path):\n",
    "        with open(path,'rb') as f:\n",
    "            base64_data = base64.b64encode(f.read())\n",
    "            return base64_data\n",
    " \n",
    "    def detect_face(self):\n",
    "        # 人脸检测与属性分析\n",
    "        # square: 正方形 triangle:三角形 oval: 椭圆 heart: 心形 round: 圆形\n",
    "        img_BASE64 = self.img_to_BASE64(self.img_src)\n",
    "        request_url = \"https://aip.baidubce.com/rest/2.0/face/v3/detect\"\n",
    "        post_data = {\n",
    "            \"image\": img_BASE64,\n",
    "            \"image_type\": \"BASE64\",\n",
    "            \"face_field\": \"face_shape,landmark\",\n",
    "            \"face_type\": \"LIVE\"\n",
    "        }\n",
    "        access_token = self.get_accessToken()\n",
    "        request_url = request_url + \"?access_token=\" + access_token\n",
    "        response = requests.post(url=request_url, data=post_data, headers=self.headers)\n",
    "        json_result = json.loads(response.text)\n",
    "        if json_result['error_msg']!='pic not has face':\n",
    "#             print(\"人脸数：\", json_result['result']['face_num'])\n",
    "#             print(\"脸型为：\",json_result['result']['face_list'][0]['face_shape']['type'])\n",
    "#             print(\"脸型的置信水平：\",json_result['result']['face_list'][0]['face_shape']['probability'])\n",
    "#             print(json_result['result']['face_list'][0]['landmark72'])\n",
    "            return json_result\n",
    "        else:\n",
    "            return None;"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 44,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1055\n"
     ]
    }
   ],
   "source": [
    "############################# 跳过这里 ##################################\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import csv\n",
    "\n",
    "csv_in = pd.read_csv('output_1.csv', sep = ',', header = None)\n",
    "# csv_in = pd.read_csv('output.csv', sep = ',', header = None)\n",
    "csv_in = csv_in.values\n",
    "img_name = csv_in[:, 1]\n",
    "img_labl = csv_in[:, 7]\n",
    "print(img_name.shape[0])\n",
    "mpFaceType = {\n",
    "    'square': '方脸',\n",
    "    'triangle':'三角脸',\n",
    "    'oval': '椭圆脸' ,\n",
    "    'heart': '心形脸',\n",
    "    'round': '圆脸'\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": false
   },
   "outputs": [],
   "source": [
    "########################## 第一次标签 #################################\n",
    "import numpy as np\n",
    "import csv\n",
    "\n",
    "csv_in = pd.read_csv('output_1.csv', sep = ',', header = None)\n",
    "csv_in = csv_in.values\n",
    "img_name = csv_in[:, 1]\n",
    "img_labl = csv_in[:, 7]\n",
    "print(img_name.shape[0])\n",
    "mpFaceType = {\n",
    "    'square': '方脸',\n",
    "    'triangle':'三角脸',\n",
    "    'oval': '椭圆脸' ,\n",
    "    'heart': '心形脸',\n",
    "    'round': '圆脸'\n",
    "}\n",
    "\n",
    "# csv_out = open('result_baiduapi.csv', 'w', newline = '')\n",
    "csv_out = open('result_baiduapi_pre.csv', 'w', newline = '')\n",
    "csv_write = csv.writer(csv_out, dialect = 'excel')\n",
    "head = ['id', 'name', 'label_origin', 'label_result', 'result_probability']\n",
    "csv_write.writerow(head)\n",
    "# csv_out = open('result_baiduapi.csv', 'a', newline = '')\n",
    "csv_out = open('result_baiduapi_pre.csv', 'a', newline = '')\n",
    "csv_write = csv.writer(csv_out, dialect = 'excel')\n",
    "\n",
    "import operator as op\n",
    "cnt = 0\n",
    "cntyes = 0\n",
    "for i in range(1, img_name.shape[0]):\n",
    "    \n",
    "    img_src = 'images/' + img_name[i][0:3] + '/' + img_name[i]\n",
    "    baiduDetect = BaiduPicIndentify(img_src)\n",
    "    json_result = baiduDetect.detect_face()\n",
    "    face_shape = json_result['result']['face_list'][0]['face_shape']['type']\n",
    "    face_shape = mpFaceType[face_shape]\n",
    "    face_shape_prob = json_result['result']['face_list'][0]['face_shape']['probability']\n",
    "    \n",
    "    if((not op.eq(img_labl[i],'方圆下巴长脸') ) and (not op.eq(img_labl[i], '尖下巴长脸'))):\n",
    "        cnt = cnt + 1\n",
    "    if(op.eq(img_labl[i], face_shape)):\n",
    "        cntyes = cntyes + 1\n",
    "        \n",
    "    eachrow = [i, img_name[i], img_labl[i], face_shape, face_shape_prob, cnt, cntyes]\n",
    "    csv_write.writerow(eachrow)\n",
    "    \n",
    "#     print(eachrow, cnt, cntyes)\n",
    "    \n",
    "    \n",
    "csv_out.close()\n",
    "  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "########################## 第二次标签 #################################\n",
    "import numpy as np\n",
    "import csv\n",
    "\n",
    "csv_in = pd.read_csv('output.csv', sep = ',', header = None)\n",
    "csv_in = csv_in.values\n",
    "img_name = csv_in[:, 1]\n",
    "img_labl = csv_in[:, 7]\n",
    "print(img_name.shape[0])\n",
    "mpFaceType = {\n",
    "    'square': '方脸',\n",
    "    'triangle':'三角脸',\n",
    "    'oval': '椭圆脸' ,\n",
    "    'heart': '心形脸',\n",
    "    'round': '圆脸'\n",
    "}\n",
    "\n",
    "csv_out = open('result_baiduapi.csv', 'w', newline = '')\n",
    "csv_write = csv.writer(csv_out, dialect = 'excel')\n",
    "head = ['id', 'name', 'label_origin', 'label_result', 'result_probability']\n",
    "csv_write.writerow(head)\n",
    "csv_out = open('result_baiduapi.csv', 'a', newline = '')\n",
    "csv_write = csv.writer(csv_out, dialect = 'excel')\n",
    "\n",
    "import operator as op\n",
    "cnt = 0\n",
    "cntyes = 0\n",
    "for i in range(1, img_name.shape[0]):\n",
    "    \n",
    "    img_src = 'images/' + img_name[i][0:3] + '/' + img_name[i]\n",
    "    baiduDetect = BaiduPicIndentify(img_src)\n",
    "    json_result = baiduDetect.detect_face()\n",
    "    face_shape = json_result['result']['face_list'][0]['face_shape']['type']\n",
    "    face_shape = mpFaceType[face_shape]\n",
    "    face_shape_prob = json_result['result']['face_list'][0]['face_shape']['probability']\n",
    "    \n",
    "    if((not op.eq(img_labl[i],'梨形脸') ) and (not op.eq(img_labl[i], '梨形脸')) and (not op.eq(img_labl[i], '长脸'))):\n",
    "        cnt = cnt + 1\n",
    "    if(op.eq(img_labl[i], face_shape)):\n",
    "        cntyes = cntyes + 1\n",
    "        \n",
    "    eachrow = [i, img_name[i], img_labl[i], face_shape, face_shape_prob, cnt, cntyes]\n",
    "    csv_write.writerow(eachrow)\n",
    "#     print(eachrow, cnt, cntyes)\n",
    "    \n",
    "csv_out.close()\n",
    "  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print('你真是个小机灵鬼')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
